package com.bstek.uflo.designer.command;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;

import com.bstek.dorado.data.provider.Page;
import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;

/**
 * @author matt.yao@bstek.com
 * @since 1.0
 */
public class QueryPageCommand implements Command<Page<?>> {

	private DetachedCriteria detachedCriteria;
	private Page<?> page;

	public QueryPageCommand(DetachedCriteria detachedCriteria, Page<?> page) {
		this.detachedCriteria = detachedCriteria;
		this.page = page;

	}

	@SuppressWarnings("unchecked")
	public Page<?> execute(Context context) {
		Session session = context.getSession();
		int pageSize = page.getPageSize();
		int startIndex = (page.getPageNo() - 1) * pageSize;
		Criteria criteria = detachedCriteria.getExecutableCriteria(session);
		criteria.setFirstResult(startIndex).setMaxResults(pageSize);
		page.setEntities(criteria.list());
		Object object = criteria.setProjection(Projections.rowCount()).uniqueResult();
		int totalCount = 0;
		if (object instanceof Long) {
			totalCount = ((Long) object).intValue();
		} else if (object instanceof Integer) {
			totalCount = (Integer) object;
		}
		page.setEntityCount(totalCount);
		return page;
	}

}
